package net.taviscaron.drivenotes.android.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;

import net.taviscaron.drivenotes.android.Constants;
import net.taviscaron.drivenotes.android.model.ApiError;
import net.taviscaron.drivenotes.android.model.ApiNotesResponse;
import net.taviscaron.drivenotes.shared.model.entity.Note;

import android.content.Context;
import android.util.Log;

public class NotesService extends BaseService {
    private static final String TAG = "NotesService";
    private static final String GARAGE_SERVICE_URL = Constants.REQUEST_URL + "token=%s&act=notes";
    
    public NotesService(Context context) {
	super(context);
    }
    
    public Note[] loadNotes() {
	InputStream is = null;
	try {
	    URL url = new URL(String.format(GARAGE_SERVICE_URL, token()));
	    Log.i(TAG, "url: " + url);
	    is = url.openStream();
 	    Log.i(TAG, "stream opened");
	    Reader reader = new InputStreamReader(is);
	    ApiNotesResponse response = gson.fromJson(reader, ApiNotesResponse.class);
	    if(response == null) {
		Log.i(TAG, "response is null");
		return null;
	    }
	    if(response.hasError()) {
		ApiError error = response.getError();
		Log.i(TAG, "error code: " + error.getCode() + "; desc: " + error.getDescription());
		return null;
	    } else {
		return response.getNotes();
	    }
	} catch (MalformedURLException e) {
	    Log.e(TAG, "bad url: " + e);
	    throw new RuntimeException(e);
	} catch (IOException e) {
	    Log.e(TAG, "ioexception: " + e);
	    return null;
    	} finally {
	    if(is != null) {
		try {
		    is.close();
		} catch (IOException e) {
		    Log.e(TAG, "can't close stream: " + e);
		}
	    }
	}
    }
}
